"""
身份认证
"""
from fastapi import Request, Depends, HTTPException
from fastapi.security import SecurityScopes
from backend.model.user import UserModel
from backend.library.database import get_db

def global_filter(req: Request, role: SecurityScopes, db=Depends(get_db)):
    """
    权限认证函数
    """

    token = req.headers.get("token")
    user = UserModel.get_user_by_token(db, token)
    if user is None:
        raise HTTPException(status_code=401, detail="无权限")
    elif user.role==1 and 'admin' in role.scopes:
        return True
    elif user.role==2 and 'teacher' in role.scopes:
        return True
    elif user.role==3 and 'student' in role.scopes:
        return True
    else:
        raise HTTPException(status_code=401, detail="无权限")